<?php

/**
 * zCaptcha actions.
 *
 * @package    sf_sandbox
 * @subpackage zCaptcha
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 2692 2006-11-15 21:03:55Z fabien $
 */
class zCaptchaActions extends sfActions
{
    /**
     * Executes index action
     *
     */
    public function executeIndex()
    {
    }

    public function executeImage()
    {

        // Begin the session
        session_start();

        // If the session is not present, set the variable to an error message
        if (!isset($_SESSION['captcha_id']))
            $str = 'ERROR!';
            // Else if it is present, set the variable to the session contents
        else
            $str = $_SESSION['captcha_id'];

        // Set the content type
        //header('Content-type: image/png');
        header('Cache-control: no-cache');

        // Create an image from button.png
        $image = imagecreatefrompng('images/captcha/button.png');

        // Set the font colour
        $colour = imagecolorallocate($image, 183, 178, 152);

        // Set the font
        $font = 'fonts/Anorexia.ttf';

        // Set a random integer for the rotation between -15 and 15 degrees
        $rotate = rand(-15, 15);

        // Create an image using our original image and adding the detail
        imagettftext($image, 14, $rotate, 18, 30, $colour, $font, $str);

        // Output the image as a png
        imagepng($image);

        return sfView::HEADER_ONLY;
    }

    public function executeNewSession()
    {
        $char = strtoupper(substr(str_shuffle('abcdefghjkmnpqrstuvwxyz'), 0, 4));

        // Concatenate the random string onto the random numbers
        // The font 'Anorexia' doesn't have a character for '8', so the numbers will only go up to 7
        // '0' is left out to avoid confusion with 'O'
        $str = rand(1, 7) . rand(1, 7) . $char;

        // Begin a new session
        session_start();

        // Set the session contents
        $_SESSION['captcha_id'] = $str;

        return sfView::HEADER_ONLY;
    }
    public function executeImageRequest()
    {

        // Echo the image - timestamp appended to prevent caching
        echo '<a href="#" id="refreshimg" title="Click to refresh image"><img src="/zCaptcha/image?' . time() . '" width="132" height="46" alt="Captcha image" /></a>';
        return sfView::HEADER_ONLY;
    }
    public function executeProcess()
    {
        // Begin the session
        session_start();

        // To avoid case conflicts, make the input uppercase and check against the session value
        // If it's correct, echo '1' as a string
        if(strtoupper($_GET['captcha']) == $_SESSION['captcha_id'])
            echo 'true';
        // Else echo '0' as a string
        else
            echo 'false';

        return sfView::HEADER_ONLY;
    }
}
